// 操作配置
import { useCallback, useMemo, useRef, forwardRef, useImperativeHandle, Ref } from 'react';
import { Form, Select, Row, Col } from 'antd';
import AuthForm, { useAuth } from '@inbiz/basic/AuthForm';
import EditableTable, { IColumns } from '@inbiz/basic/EditableTable';
import style from './operation.less';
import operationFlagTitle from '@components/form/grade/Table/operationFlagTitle';

import { getMessage } from '@inbiz/react';
import { uuid } from '@inbiz/utils';

export const options = [
  { value: 1, label: '文字' },
  { value: 2, label: '图标' },
  { value: 3, label: '图标+文字' },
];
const typeOptions = [
  { label: '新增', value: 'add' },
  { label: '删除', value: 'del' },
  { label: '彻底删除', value: 'thoroughDel' },
  { label: '恢复', value: 'recovery' },
  { label: '导出', value: 'export' },
  { label: '导入', value: 'import' },
  { label: '打印', value: 'print' },
  { label: '自定义', value: 'custom' },
];
export type IOperationRef = {
  getValue: (authSumbmit?: boolean) => Promise<IOperationData>;
};

function Operation(
  {
    value,
    isInTable,
  }: {
    isInTable?: boolean; // 配置控件是否在table中
    value?: IOperationData;
  },
  ref: Ref<IOperationRef>,
) {
  const [form] = Form.useForm();
  const tableRef = useRef<any>(null);
  const [choosedAuth, changeHandle, generateFlag] = useAuth();

  const authOption = useMemo(() => {
    return (choosedAuth?.allInfo?.Children || []).map((ele: any) => ({
      value: ele.ObjectValue,
      label: ele.ObjectValue + `(${getMessage(ele.ObjectName)})`,
    }));
  }, [choosedAuth]);

  const initialValues = useMemo(() => {
    return {
      auth: value?.auth,
      showType: value?.showType ?? 1,
    };
  }, [value]);

  const columns = useMemo(() => {
    return [
      isInTable
        ? {
          dataIndex: 'type',
          title: '操作类型',
          width: 100,
          editData: {
            type: 'Select',
            allowClear: true,
            defaultOpen: true,
            options: typeOptions,
            rules: [{ required: true }],
            afterEdit: (value: string, recerd: { name: string }) => {
              recerd.name = 'EformButtonGroup.button.' + value;
              return recerd;
            },
          },
        }
        : {
          title: '操作名称',
          dataIndex: 'name',
          width: 100,
          editData: {
            type: 'MultilingualInput',
            rules: [{ required: true }],
          },
        },
      {
        dataIndex: 'flag',
        title: operationFlagTitle(),
        //  'operationFlagTitle',//不加字符串
        width: 150,
        editData: {
          type: 'AutoComplete',
          options: authOption || [],
        },
        isIdentical: true,
        isIdenticalTitle: '标识',
      },
      isInTable
        ? {
          title: '操作名称',
          dataIndex: 'name',
          width: 100,
          editData: {
            type: 'MultilingualInput',
            rules: [{ required: true }],
          },
        }
        : undefined,
      {
        title: '页面',
        dataIndex: 'page',
        width: 100,
        editData: {
          beforEdit: (recerd: { type: string }) => {
            return recerd.type === 'custom';
          },
          type: 'PageSelect',
        },
      },
      {
        title: '按钮图标',
        dataIndex: 'icon',
        width: 100,
        editData: {
          type: 'IconPicker',
          showIconSize: false,
          showColorPicker: false,
        },
      },
      {
        dataIndex: 'openType',
        title: '打开方式',
        width: 100,
        editData: {
          beforEdit: (recerd: { type: string }) => {
            return recerd.type === 'custom' || recerd.type === 'add';
          },
          type: 'Select',
          allowClear: true,
          defaultOpen: true,
          options: [
            { label: '弹窗', value: 'modal' },
            { label: '抽屉-上', value: 'top' },
            { label: '抽屉-下', value: 'bottom' },
            { label: '抽屉-左', value: 'left' },
            { label: '抽屉-右', value: 'right' },
            { label: '当前窗口', value: 'current' },
          ],
        },
      },
      {
        title: '窗体名称',
        dataIndex: 'windowName',
        width: 100,
        editData: {
          beforEdit: (recerd: { type: string }) => {
            return recerd.type === 'custom' || recerd.type === 'add';
          },
          type: 'MultilingualInput',
        },
      },
      {
        title: '分隔符',
        dataIndex: 'separator',
        width: 100,
        editData: {
          type: 'Switch',
        },
        render: (value: undefined) => {
          if (value !== undefined) {
            return value ? '显示' : '隐藏';
          } else {
            return '';
          }
        },
      },
    ].filter((item) => !!item) as IColumns;
  }, [isInTable, authOption]);

  const handleAdd = useCallback(() => {
    return { id: uuid(10, 5), type: isInTable ? '' : 'custom' };
  }, [isInTable]);
  useImperativeHandle(
    ref,
    () => ({
      getValue: async (authSumbmit) => {
        const formData = form.getFieldsValue(true);
        const list: IOperationData['list'] = await tableRef.current!.getData();
        if (authSumbmit) {
          // 保存权限标识到后台
          const flags = list
            .filter((item) => item.flag)
            .map((item) => ({ value: item.flag!, label: item.name }));
          await generateFlag(flags);
        }
        return {
          ...formData,
          auth: formData.auth?.value,
          list,
        };
      },
    }),
    [generateFlag],
  );
  const dataSource = useMemo(() => value?.list || [], [value?.list]);
  return (
    <div className={style.operationBox}>
      <Form form={form} initialValues={initialValues} colon={false}>
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item name="auth" label="动作权限分组">
              {/* @ts-ignore */}
              <AuthForm withoutForm inFormItem onChange={changeHandle} />
            </Form.Item>
          </Col>
          <Col span={8} offset={4}>
            <Form.Item name="showType" label="操作按钮显示">
              <Select options={options} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <EditableTable
        className="editable-table"
        dataSource={dataSource}
        rowKey={'id'}
        columns={columns}
        rowSelection={{ columnWidth: 44 }}
        onAdd={handleAdd}
        scroll={{ y: 260 }}
        ref={tableRef}
      />
    </div>
  );
}

export default forwardRef(Operation);

export type IOperationData = {
  auth?: string; //动作权限分组数据
  showType: 1 | 2 | 3; //按钮显示类型 1 文字, 2 图标 ，文字图标
  list: {
    id: string; // 唯一id
    type: 'add' | 'del' | 'recovery' | 'thoroughDel' | 'export' | 'import' | 'print' | 'custom'; //类型
    flag?: string; // 标识
    name: string; //名称
    page?: string; // 页面
    icon?: { color?: string; type: string }; //图标
    openType?: 'modal' | 'top' | 'left' | 'right' | 'bottom' | 'current'; //打开方式
    windowName?: string; //窗体名称
    separator?: boolean; // 分割符
  }[];
};
